using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Process;
using WPF_MVVM_Test.MVVM_ViewModel;
using WPF_MVVM_Test.Services.Process;

namespace WPF_MVVM_Test.MVVM_ViewModel.Process_process
{
    /// <summary>
    /// 工艺路线管理ViewModel
    /// </summary>
    public class ProcessRouteManagementViewModel : BaseViewModel
    {
        private readonly ProcessRouteService _processRouteService;
        private ObservableCollection<ProcessRoute> _processRoutes;
        private ProcessRoute? _selectedProcessRoute;
        private string _statusFilter = "";
        private int _currentPage = 1;
        private int _totalPages = 1;
        private int _pageSize = 10;
        private int _totalItems = 0;
        private bool _isLoading;

        public ProcessRouteManagementViewModel()
        {
            _processRouteService = new ProcessRouteService();
            _processRoutes = new ObservableCollection<ProcessRoute>();

            // 初始化命令
            LoadDataCommand = new AsyncRelayCommand(async () => await LoadProcessRoutesAsync());
            AddCommand = new RelayCommand(ExecuteAdd);
            RefreshCommand = new AsyncRelayCommand(async () => await LoadProcessRoutesAsync());
            FirstPageCommand = new AsyncRelayCommand(async () => await GoToFirstPageAsync(), () => CanGoToFirstPage);
            PreviousPageCommand = new AsyncRelayCommand(async () => await GoToPreviousPageAsync(), () => CanGoToPreviousPage);
            NextPageCommand = new AsyncRelayCommand(async () => await GoToNextPageAsync(), () => CanGoToNextPage);
            LastPageCommand = new AsyncRelayCommand(async () => await GoToLastPageAsync(), () => CanGoToLastPage);
            SearchCommand = new AsyncRelayCommand(async () => await SearchAsync());

            // 初始化状态筛选选项
            StatusOptions = new ObservableCollection<string> { "全部", "启用", "停用" };
            SelectedStatus = "全部";

            // 加载数据
            LoadDataCommand.Execute(null);
        }

        #region 属性

        /// <summary>
        /// 工艺路线列表
        /// </summary>
        public ObservableCollection<ProcessRoute> ProcessRoutes
        {
            get => _processRoutes;
            set => SetProperty(ref _processRoutes, value);
        }

        /// <summary>
        /// 选中的工艺路线
        /// </summary>
        public ProcessRoute? SelectedProcessRoute
        {
            get => _selectedProcessRoute;
            set => SetProperty(ref _selectedProcessRoute, value);
        }

        /// <summary>
        /// 状态筛选
        /// </summary>
        public string StatusFilter
        {
            get => _statusFilter;
            set => SetProperty(ref _statusFilter, value);
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurrentPage
        {
            get => _currentPage;
            set
            {
                if (SetProperty(ref _currentPage, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    UpdatePageCommands();
                }
            }
        }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages
        {
            get => _totalPages;
            set
            {
                if (SetProperty(ref _totalPages, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                    UpdatePageCommands();
                }
            }
        }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalItems
        {
            get => _totalItems;
            set
            {
                if (SetProperty(ref _totalItems, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                }
            }
        }

        /// <summary>
        /// 是否正在加载
        /// </summary>
        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        /// <summary>
        /// 分页信息
        /// </summary>
        public string PageInfo => $"第 {CurrentPage} 页，共 {TotalPages} 页，总计 {TotalItems} 条";

        /// <summary>
        /// 状态选项
        /// </summary>
        public ObservableCollection<string> StatusOptions { get; }

        /// <summary>
        /// 选中的状态
        /// </summary>
        public string SelectedStatus
        {
            get => StatusFilter == "" ? "全部" : StatusFilter;
            set
            {
                var filterValue = value == "全部" ? "" : value;
                if (SetProperty(ref _statusFilter, filterValue))
                {
                    OnPropertyChanged(nameof(SelectedStatus));
                }
            }
        }

        #endregion

        #region 命令

        public ICommand LoadDataCommand { get; }
        public ICommand AddCommand { get; }
        public ICommand RefreshCommand { get; }
        public ICommand FirstPageCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand LastPageCommand { get; }
        public ICommand SearchCommand { get; }

        #endregion

        #region 分页相关

        private bool CanGoToFirstPage => CurrentPage > 1;
        private bool CanGoToPreviousPage => CurrentPage > 1;
        private bool CanGoToNextPage => CurrentPage < TotalPages;
        private bool CanGoToLastPage => CurrentPage < TotalPages;

        private async Task GoToFirstPageAsync()
        {
            CurrentPage = 1;
            await LoadProcessRoutesAsync();
        }

        private async Task GoToPreviousPageAsync()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                await LoadProcessRoutesAsync();
            }
        }

        private async Task GoToNextPageAsync()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                await LoadProcessRoutesAsync();
            }
        }

        private async Task GoToLastPageAsync()
        {
            CurrentPage = TotalPages;
            await LoadProcessRoutesAsync();
        }

        private void UpdatePageCommands()
        {
            (FirstPageCommand as AsyncRelayCommand)?.RaiseCanExecuteChanged();
            (PreviousPageCommand as AsyncRelayCommand)?.RaiseCanExecuteChanged();
            (NextPageCommand as AsyncRelayCommand)?.RaiseCanExecuteChanged();
            (LastPageCommand as AsyncRelayCommand)?.RaiseCanExecuteChanged();
        }

        #endregion

        #region 命令执行方法

        /// <summary>
        /// 加载工艺路线数据
        /// </summary>
        private async Task LoadProcessRoutesAsync()
        {
            try
            {
                IsLoading = true;
                System.Diagnostics.Debug.WriteLine($"开始加载工艺路线数据，页码: {CurrentPage}，状态筛选: {StatusFilter}");

                var response = await _processRouteService.GetProcessRoutePagedAsync(
                    status: StatusFilter,
                    pageIndex: CurrentPage,
                    pageSize: _pageSize
                );

                if (response.IsSuc)
                {
                    System.Diagnostics.Debug.WriteLine($"工艺路线数据加载成功，数据数量: {response.Data.Data.Count}");

                    ProcessRoutes.Clear();
                    foreach (var item in response.Data.Data)
                    {
                        ProcessRoutes.Add(item);
                    }

                    TotalItems = response.Data.TotalCount;
                    TotalPages = response.Data.TotalPage;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"工艺路线数据加载失败: {response.Msg}，使用测试数据");
                    LoadTestData();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"工艺路线数据加载异常: {ex.Message}，使用测试数据");
                LoadTestData();
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 加载测试数据
        /// </summary>
        private void LoadTestData()
        {
            ProcessRoutes.Clear();

            var testData = new[]
            {
                new ProcessRoute
                {
                    Id = "9cf33499-8615-4ac8-8df4-9275db039d0b",
                    ProcessRouteNumber = "GY20241201002",
                    ProcessRouteName = "改良产品工艺路线",
                    Status = "启用",
                    Description = "用于改良产品的生产工艺路线，包含预处理、主加工、精加工、检验、包装等主要工序",
                    Remark = "优化版本，加入了更多的精加工步骤以提高产品质量",
                    IsActive = true,
                    VersionDescription = "V1.1 优化版本 - 增加精加工步骤",
                    PreviousVersionId = "d5c88c60-5a7f-4c3b-adc7-34f017daf300",
                    ProcessStepCount = 3
                },
                new ProcessRoute
                {
                    Id = "b00fe53d-9eb2-4938-87d4-7a45755dcd0b",
                    ProcessRouteNumber = "GY20241201001",
                    ProcessRouteName = "新产品工艺路线",
                    Status = "启用",
                    Description = "用于新产品生产的标准工艺路线，包含预处理、加工、检验、包装等主要工序",
                    Remark = "初始版本，后续根据生产情况进行优化调整",
                    IsActive = true,
                    VersionDescription = "V1.0 初始版本 - 基础工艺流程",
                    PreviousVersionId = null,
                    ProcessStepCount = 5
                }
            };

            foreach (var item in testData)
            {
                ProcessRoutes.Add(item);
            }

            TotalItems = ProcessRoutes.Count;
            TotalPages = 1;
        }

        /// <summary>
        /// 执行新增
        /// </summary>
        private void ExecuteAdd()
        {
            try
            {
                MessageBox.Show("新增工艺路线功能待实现", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"新增工艺路线时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 执行搜索
        /// </summary>
        private async Task SearchAsync()
        {
            CurrentPage = 1;
            await LoadProcessRoutesAsync();
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _processRouteService?.Dispose();
            }
            base.Dispose(disposing);
        }
    }

    /// <summary>
    /// 异步RelayCommand实现
    /// </summary>
    public class AsyncRelayCommand : ICommand
    {
        private readonly Func<Task> _executeAsync;
        private readonly Func<bool>? _canExecute;

        public AsyncRelayCommand(Func<Task> executeAsync, Func<bool>? canExecute = null)
        {
            _executeAsync = executeAsync ?? throw new ArgumentNullException(nameof(executeAsync));
            _canExecute = canExecute;
        }

        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return _canExecute?.Invoke() ?? true;
        }

        public async void Execute(object? parameter)
        {
            await _executeAsync();
        }

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}